package net.gazhi.delonix.weixin.mp.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import net.gazhi.delonix.weixin.mp.MPConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

public abstract class MpMsgControllerSupport {

	protected Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private MPConfig mpConfig;

	/**
	 * 绑定微信服务器
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public final String bind(HttpServletRequest request) {
		boolean result = SignatureUtil.checkSignature(request, mpConfig.getToken());
		if (result) {
			logger.info("AppId=" + mpConfig.getAppId() + ", Bound successfully!");
		} else {
			logger.warn("AppId=" + mpConfig.getAppId() + ", Fail to bind!");
		}
		return result ? request.getParameter("echostr") : "Fail to bind!";
	}

	/**
	 * 微信消息交互处理
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public final String process(HttpServletRequest request) throws ServletException, IOException {
		boolean result = SignatureUtil.checkSignature(request, mpConfig.getToken());
		if (!result) {
			return "";
		}
		Map<String, String> reqMap = MessageUtil.parseXml(request);
		logger.info(reqMap);
		return "";
	}

}
